﻿using AutoMapper;
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.Extensions.Logging;
using ShanNiang.Hosting;
using ShanNiang.Hosting.Extensions;
using ShanNiang.Service.Attributes;
using ShanNiang.Service.Constants;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ShanNiang.Mvvm.ViewModels
{
    /// <summary>
    /// 直接绑定在UI上当的viewmodel
    /// 例如 Window，UserControl，Page
    /// 使用本基类 可以快速依赖注入
    /// </summary>
    public abstract class UIViewModel : ObservableRecipient
    {

        static readonly string DataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), CommonData.DataFolder);
        static UIViewModel()
        {
            if (!Directory.Exists(DataFolder))
            {
                Directory.CreateDirectory(DataFolder);
            }
        }
        protected IMapper Mapper { get; private set; }
        protected ILogger<UIViewModel> Logger { get; private set; }
        protected UIViewModel(IMapper mapper, ILogger<UIViewModel> logger)
        {
            Mapper = mapper;
            Logger = logger;
        }

        public void LoadData()
        {
            var type = this.GetType();
            var viewModelAttribute = type.GetCustomAttribute<ViewModelFileAttribute>();
            if (viewModelAttribute != null)
            {
                try
                {
                    var filePath = Path.Combine(DataFolder, $"{HostingExtensions.GetEnvName()}_{viewModelAttribute.FileName}");
                    if (File.Exists(filePath))
                    {
                        var json = File.ReadAllText(filePath);
                        var model = json.FromJson(viewModelAttribute.SaveType);
                        if (model != null)
                        {
                            Mapper.Map(model, this);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "【缓存读取】报错了");
                }
            }
        }
        public void SaveData()
        {
            var type = this.GetType();
            var viewModelAttribute = type.GetCustomAttribute<ViewModelFileAttribute>();
            if (viewModelAttribute != null)
            {
                try
                {
                    var filePath = Path.Combine(DataFolder, $"{HostingExtensions.GetEnvName()}_{viewModelAttribute.FileName}");
                    var model = Mapper.Map(this, GetType(), viewModelAttribute.SaveType);
                    var json = model.ToJson();
                    File.WriteAllText(filePath, json);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "【缓存写入】报错了");
                }
            }
        }
    }
}
